package com.example.springbootdockertest.controller.excel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ExcelDemoListener extends AnalysisEventListener<ExcelDemo> {

    private static final Logger log = LoggerFactory.getLogger(ExcelDemoListener.class);
    //worker线程池配置
    private static final int workerThreadNum = 10;
    private static final String workerThreadName = "ExcelDemo-Pool-%d";
    private static ExecutorService workerThreadPool;

    Map<String, String> map = new ConcurrentHashMap<>();
    private String token;
    private String platform;

    public ExcelDemoListener() {
    }

    public ExcelDemoListener(String token, String platform) {
        this.token = token;
        this.platform = platform;
    }


    /**
     * 解析上传的Excel 存入map
     *
     * @param excelDemo       对应上传的Excel文件实体类
     * @param analysisContext
     * @return void
     */
    @Override
    public void invoke(ExcelDemo excelDemo, AnalysisContext analysisContext) {
        map.put(excelDemo.getId(), excelDemo.getManifestId());

    }

    /**
     * 对map中的数据进行处理 多线程请求
     *
     * @param analysisContext
     * @return void
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //Excel 中的运单轨迹id为map的key 运单id(manifestId)为map的value
        //登录获取token
        //切换访问URL
        System.out.println(map);
        String format = "";
        if (Objects.equals(platform, "kec")) {
            //kec
            // format = "https://tms-kec.kerry-ecommerce.com.cn/tms-saas-web/tms/manifestpod/del?id={}&manifestId={}&token={}";
            format = "https://tms-kec.kerry-ecommerce.com.cn/tms-saas-web/tms/manifestpod/del?id={}&manifestId={}&token={}";
        } else {
            //kp
            format = "https://tms-kp.kerry-ecommerce.com.cn/tms-saas-web/tms/manifestpod/del?id={}&manifestId={}&token={}";
        }
        AtomicInteger count = new AtomicInteger(0);
        String finalFormat = format;

        // getWorkerThreadPool().submit(() -> {
        //     map.forEach((id, manifestId) -> {
        //         String url = StrUtil.format(finalFormat, id, manifestId, token);
        //         HttpResponse execute = HttpRequest.post(url).execute();
        //         log.info("id==>{};manifestId==>{};count==>{}", id, manifestId, count.incrementAndGet());
        //         log.info("isOk==>{};result==>{};url==>{}", execute.isOk(), JSONUtil.parseObj(execute.body()).get("message"), url);
        //     });
        // });

        map.forEach((id, manifestId) -> {
            getWorkerThreadPool().submit(() -> {
                String url = StrUtil.format(finalFormat, id, manifestId, token);
                HttpResponse execute = HttpRequest.post(url).execute();
                log.info("id==>{};manifestId==>{};count==>{}", id, manifestId, count.incrementAndGet());
                log.info("isOk==>{};result==>{};url==>{}", execute.isOk(), JSONUtil.parseObj(execute.body()).get("message"), url);
            });
        });
    }

    /**
     * 获取或者创建,worker线程池
     */
    private ExecutorService getWorkerThreadPool() {
        if (workerThreadPool != null) {
            return workerThreadPool;
        }
        BasicThreadFactory build = new BasicThreadFactory.Builder().namingPattern(workerThreadName).daemon(true).build();

        workerThreadPool = new ThreadPoolExecutor(workerThreadNum
                , workerThreadNum
                , 0L
                , TimeUnit.SECONDS
                , new LinkedBlockingQueue<Runnable>()
                , build
                , new ThreadPoolExecutor.AbortPolicy());

        return workerThreadPool;
    }
}
